package com.njh.tools.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.njh.tools.R;
import com.njh.tools.base.util.TUtil;
import com.njh.tools.common.AppManager;
import com.njh.tools.common.string.StringUtils;
import com.njh.tools.config.tconstant.Constants;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.concurrent.TimeUnit;

import me.yokeyword.fragmentation_swipeback.SwipeBackActivity;
import rx.Observable;

/**
 * Created by niejiahuan on 2016/5/31.
 * 父类activity
 */
public abstract class BaseActivity<T extends BasePresenter, E extends BaseModel> extends SwipeBackActivity implements BaseView {
    public  T mPresenter;//UI控制层
    public E mModel;//数据操作层
    public long mExitTime;
    public boolean isNeedConfirmAppExit = false;
    protected TextView toolbar_header;
    protected Toolbar toolbar;
    protected ProgressDialog mProgressDialog;
    protected BaseActivity mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mContext = this;
        super.onCreate(savedInstanceState);

        // 修改状态栏文字为灰色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        if (this.getLayoutId() != 0) {
            this.setContentView(this.getLayoutId());
            mPresenter = TUtil.getT(this, 0);
            mModel = TUtil.getT(this, 1);
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getResources().getString(R.string.waitting));
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(true);
            AppManager.getAppManager().addActivity(this);
            this.initPresenter();
            this.initView();
        } else {
            throw new RuntimeException("Class need add LayoutId");
        }
    }

    public void setNeedConfirmAppExit(boolean needConfirmAppExit) {
        isNeedConfirmAppExit = needConfirmAppExit;
    }

    /**
     * 获取布局文件
     *
     * @return
     */
    public abstract int getLayoutId();


    /**
     * 初始化视图操作
     */
    public abstract void initView();

    protected void initEvent() {
    }

    /**
     * 简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
     */
    public abstract void initPresenter();

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (isNeedConfirmAppExit) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                    return false;
                } else {
                    AppManager.getAppManager().AppExit(this);
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 防抖动，防止快速点击
     *
     * @param observable
     * @param <T>
     * @return
     */
    protected <T extends Object> Observable<T> throttleFirst(Observable<T> observable) {
        return observable.throttleFirst(Constants.WINDOW_DURATION, TimeUnit.MILLISECONDS);
    }

    /**
     * 将事件与生命周期绑定
     *
     * @param observable
     * @return
     */
    protected <T extends Object> Observable<T> bindLife(Observable<T> observable) {
        return (Observable<T>) observable.compose(bindToLifecycle());
    }

    /**
     * 指定事件在哪个生命周期结束
     *
     * @param observable
     * @param event      生命周期
     * @return
     */
    protected <T extends Object> Observable<T> bindUntil(Observable<T> observable, ActivityEvent event) {
        return (Observable<T>) observable.compose(bindUntilEvent(event));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        if (null != mPresenter) {
            mPresenter.onDestroy();
        }
        AppManager.getAppManager().finishActivity(this);
        super.onDestroy();
    }

    //初始化toolbar
    protected void initToolbar(int title, boolean showNavigationIcon, boolean menuItemClick, final OnMenuClickListener onMenuClickListener) {
//        initToolbar(this.getResources().getString(title), showNavigationIcon, menuItemClick, onMenuClickListener);
    }

    //初始化toolbar
//    protected void initToolbar(String title, boolean showNavigationIcon, boolean menuItemClick, final OnMenuClickListener onMenuClickListener) {
//        toolbar = (Toolbar) findViewById(R.id.toolbar);
//        toolbar_header = (TextView) findViewById(R.id.toolbar_title_tv);
//        toolbar.setTitle("");
//        toolbar_header.setText(title);
//        setSupportActionBar(toolbar);
//        if (showNavigationIcon) {
//            toolbar.setNavigationIcon(R.mipmap.go_back);
//            // Menu item click 的監聽事件一樣要設定在 setSupportActionBar 才有作用
//            // toolbar.setOnMenuItemClickListener(onMenuItemClick);
//            //设置toolbar右侧的点击事件
//            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    finish();
//                }
//            });
//        }
//        if (menuItemClick) {
//            toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//                @Override
//                public boolean onMenuItemClick(MenuItem item) {
//                    onMenuClickListener.onItemClick(item);
//                    return false;
//                }
//            });
//        }
//    }

    //点击事件的回调
    public interface OnMenuClickListener {
        void onItemClick(MenuItem item);
    }
    public void setTextValue(TextView tv, String value) {
        if (!StringUtils.isEmpty(value)) {
            tv.setVisibility(View.VISIBLE);
            tv.setText(value);
        } else {
            tv.setVisibility(View.GONE);
        }
    }
    /**
     * 获取资源文件
     *
     * @param sId
     * @return
     */
    public String getRString(int sId) {
        return this.getResources().getString(sId);
    }


    @Override
    public void showError(Throwable e) {
        hideLoading();
//        if (e instanceof ApiException) {
//            if (Constants.LOGIN_NO_CODE.equals(((ApiException) e).getReturnCode())) {
//                RxBusUtil.getDefault().post(new Event(Event.LOGOUT_LOSE_EFFICACY, "您的账号在异地登陆，请重新登陆"));
//                return;
//            }
//            ToastUtil.getInstance().show(((ApiException) e).getMsg());
//        } else {
//            ToastUtil.getInstance().show(R.string.connect_fail);
//            LogUtils.wtf(e);
//        }

    }

    @Override
    public void showLoading() {
        if (mProgressDialog != null && (!mProgressDialog.isShowing())) {
            mProgressDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
    /**
     * 打开软键盘
     */
    public static void openKeybord(EditText mEditText, Context mContext)
    {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    /**
     * 关闭系统的软键盘
     * @param activity
     */
    public static void dismissSoftKeyboard(Activity activity) {

        View view = activity.getWindow().peekDecorView();
        if (view != null)
        {
            InputMethodManager inputmanger = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

    }
}
